package com.chang.bootplus.controller;

import cn.hutool.core.lang.UUID;
import com.chang.bootplus.base.annotation.PublicVisit;
import com.chang.bootplus.base.constant.Constant;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.RedisUtil;
import com.chang.bootplus.vo.CaptchaVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.annotation.processing.Processor;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import com.google.code.kaptcha.Producer;

@RestController
@Api(tags = {"图片验证码"})
@CrossOrigin(origins = "*")
public class CaptchaController {

    @Resource
    Producer producer;
    @Autowired
    RedisUtil redisUtil;
    @PostMapping("/getcaptcha")
    @PublicVisit
    @ApiOperation(httpMethod = "POST", value = "获取验证码")
    public ApiResponse<CaptchaVO> getcaptcha() throws IOException {
        String key = UUID.randomUUID().toString();

        String code = producer.createText();
        System.out.println(key);
        System.out.println(code);

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());
        redisUtil.hset(Constant.CAPTCHA_KEY, key, code, 1200);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setBase64Img(base64Img).setCaptchakey(key);
        return new ApiResponse(captchaVO);
    }

}
